<?php

use Yaf\Controller_Abstract;

class AccountController extends Controller_Abstract
{
    public function addAction()
    {
        $request = $this->getRequest();
        $user = $request->getParam('userInfo');

        if (!$this->checkType($user['type'])) {
            return ResponeMessage::clientErrMsg("非法操作，该用户没有权限!");
        }

        $post = $request->getPost();
        if (!isset($post['username']) || !isset($post['password']) || !isset($post['type'])) {
            return ResponeMessage::clientErrMsg("username，password，type 不存在!");
        }

        $path = Config::get('user.savadir');

        $insert = [
            'username' => $post['username'],
            'password' => $post['password'],
            'md5Pwd' => md5('123'),
            'type' => $post['type']
        ];

        $user = MysqlDb::getDb()->where('username', $post['username'])->getOne('account');
        if (!empty($user)) {
            return ResponeMessage::clientErrMsg("该账号已经添加过了!");
        }


        $id = MysqlDb::getDb()->insert('account', $insert);
        if (!$id) {
            return ResponeMessage::serviceErrMsg("添加失败!");
        }

        $savaDir = "{$path}user_{$id}/";
        $userModel = new UserModel(compact('savaDir'));
        if (!file_exists($savaDir)) {
            if (!mkdir($savaDir, 0777, true)) {
                MysqlDb::getDb()->where('id', $id)->delete('account');
                return ResponeMessage::serviceErrMsg("创建文件失败!");
            }
            mkdir($userModel->getCookieFile(), 0777, true);
            mkdir($userModel->getDataFile(), 0777, true);

        }

        $res = MysqlDb::getDb()->where('id', $id)->update('account', compact('savaDir'));
        if (!$res) {
            return ResponeMessage::serviceErrMsg("修改失败!");
        }
        return ResponeMessage::sucessMsg("添加成功!", compact('id'));
    }


    /**
     * 检查用户是不是超级管理员
     * @param $userType
     * @return bool
     */
    private function checkType($userType): bool
    {
        return $userType == 0;

    }


    /**
     * 修改接口
     * @return array|bool
     * @throws Exception
     */
    public function updateAction()
    {
        $request = $this->getRequest();
        $user = $request->getParam('userInfo');

        if (!$this->checkType($user['type'])) {
            return ResponeMessage::clientErrMsg("非法操作，该用户没有权限!");
        }

        $post = $request->getPost();

        if (MysqlDb::getDb()->where('id', $post['id'])->update('account', [
            'password' => $post['password'],
            'md5Pwd' => md5(trim($post['password'])),
            'type' => (int)$post['type'],
        ])) {
            return ResponeMessage::sucessMsg("修改成功!");
        }
        return ResponeMessage::clientErrMsg("修改失败," . MysqlDb::getDb()->getLastError());
    }


    /**
     * 删除接口
     * @return array|bool
     * @throws Exception
     */
    public function delAction()
    {
        $request = $this->getRequest();
        $user = $request->getParam('userInfo');

        if (!$this->checkType($user['type'])) {
            return ResponeMessage::clientErrMsg("非法操作，该用户没有权限!");
        }

        $get = $request->getQuery();

        $user = MysqlDb::getDb()->where('id', $get['id'])->getOne('account');
        if (empty($user)) {
            return ResponeMessage::clientErrMsg("该账号不存在!");
        }

        if (MysqlDb::getDb()->where('id', $get['id'])->delete('account')) {
            //删除文件
            del_dir((new UserModel($user))->getSavaDir());
            return ResponeMessage::sucessMsg("删除成功!");
        }
        return ResponeMessage::serviceErrMsg("删除失败!");
    }


    /**
     * 删除接口
     * @return array|bool
     * @throws Exception
     */
    public function listAction()
    {
        $request = $this->getRequest();
        $user = $request->getParam('userInfo');

        if (!$this->checkType($user['type'])) {
            return ResponeMessage::clientErrMsg("非法操作，该用户没有权限!");
        }


        $get = $request->getQuery();

        $page = $get['page'] ?? 1;

        MysqlDb::getDb()->pageLimit = $get['size'] ?? 1;
        $db = MysqlDb::getDb();
        if (isset($get['username']) && !empty($get['username'])) {
            $db->where('username', $get['username'] . '%', 'like');
        }
        $list = $db->orderBy('id', 'asc')->arraybuilder()->paginate("account", $page);
        foreach ($list as &$item) {
            $model = new UserModel($item);
            $item['typeString'] = $model->typeToString();
        }
        return ResponeMessage::sucessMsg("获取成功!", [
            'list' => $list,
            'total' => (int)MysqlDb::getDb()->totalCount,
            'size' => $get['size'] ?? 1,
            'page' => $page,
            'page_sum' => MysqlDb::getDb()->totalPages
        ]);
    }
}